import os,datetime,tkinter
import tkinter.messagebox
import filescan as sc
import excel as ex
import mkdir as mk
import target as tg
import wordtopdf as pdf
from docx import Document
from docx import shared
import traceback

# 是否需要转为 pdf 格式
to_pdf = 1

# 每个人改一次
teacher_name = "苏卫朋"
image_suffix = ".jpg"

# 不需要改动
left_space   = "  "
doc_from = r'template.docx'
doc_to   = ""
direction_list = []
check   = 9745
uncheck = 9744
student_name_list = []

def table_replace(doc, excel_sheet, cl_row, st_row, img_path):
    cell_set = []
    for table in doc.tables:
       for row in table.rows:
           for cell in row.cells:
                if cell.text not in cell_set:
                    cell_set.append(cell.text)
                    for paragraph in cell.paragraphs:
                        for run in paragraph.runs:
                            if run.text.strip() == "date":
                                date_string = ex.get_date(excel_sheet, st_row)
                                Y = date_string[0:4]
                                m = date_string[4:6]
                                d = date_string[6:8]
                                run.text = left_space+("%s-%s-%s")%(Y,m,d)      
                            if run.text.strip() == "teacher":
                                run.text = left_space+teacher_name
                            if run.text.strip() == "directions":                                
                                directions = []
                                ex.get_direction(directions)
                                direction_list=ex.get_direction_num(cl_row)
                                directions_str = ""
                                dir_num = 0
                                ch = chr(uncheck)
                                for direction in directions:
                                    dir_num += 1
                                    if str(dir_num) in direction_list:
                                        ch = chr(check)
                                    else:
                                        ch = chr(uncheck)
                                    directions_str = directions_str+ch+direction+2*left_space
                                run.text = left_space+directions_str.rstrip()
                            if run.text.strip() == "stage":
                                replace_text = ex.get_stage(cl_row)
                                if replace_text is not None:
                                    run.text = left_space+replace_text
                            if run.text.strip() == "class name":
                                replace_text = ex.get_class_name(cl_row)
                                if replace_text is not None:
                                    run.text = left_space+replace_text
                            if run.text.strip() == "target":
                                replace_text = ex.get_target(cl_row)
                                if replace_text is not None:
                                    run.text = left_space+replace_text
                            if run.text.strip() == "fields":
                                fields = []
                                ex.get_fields(fields)
                                field_list=ex.get_field_num(cl_row)
                                field_str = ""
                                field_num = 0
                                ch = chr(uncheck)
                                for field in fields:
                                    field_num += 1
                                    if str(field_num) in field_list:
                                        ch = chr(check)
                                    else:
                                        ch = chr(uncheck)+" "
                                    field_str = field_str+ch+field+" "
                                    if(field_num == 10):
                                        field_str += '\n'
                                run.text = field_str.rstrip()
                            if run.text.strip() == "duty":
                                replace_text = ex.get_duty(cl_row)
                                if replace_text is not None:
                                    run.text = left_space+replace_text
                            if run.text.strip() == "teacher say":
                                replace_text = ex.get_teacher_say(sht=excel_sheet,who=st_row)
                                if replace_text is not None:
                                    run.text = replace_text
                            if run.text.strip() == "parent say":
                                run.text = ""
                            if run.text.strip() == "photo":
                                run.text = ""
                                if img_path is not None:
                                    run.add_picture(img_path,height=shared.Cm(5))
                                                                     
def paragraph_replace(doc, excel_sheet,st_row):
    for p in doc.paragraphs:
        for run in p.runs:
            if run.text.strip() == "evaluation":
                rows    = ex.get_evaluation_item_rows()
                columns = ex.get_evaluation_result_rows()
                evaluation_str = ""
                for row in range(0,rows):
                    res = ex.get_item_result(sht=excel_sheet,item=row,who=st_row)
                    evaluation_str += "%2d"%(row+1)+13*" "
                    item = ex.get_evaluation_item(row)
                    offset_space = (6-len(item))*2*" "
                    evaluation_str += item + offset_space + 9*" "
                    for check_state in range(0, columns):
                        if check_state+1==res:
                            evaluation_str += chr(check)
                            evaluation_str += 11*" "
                        else:
                            evaluation_str += chr(uncheck)
                            evaluation_str += 12*" "
                    evaluation_str = evaluation_str.rstrip()
                    evaluation_str += '\n'
                run.text = evaluation_str

def generating(str_sheet,list_rows):
    try:
        copy_num = len(list_rows)
        for i in range(0, copy_num):
            student_num_from_excel = ex.get_student_number(str_sheet,list_rows[i])
            date_from_excel        = ex.get_date(str_sheet,list_rows[i])
            mk.make(student_num_from_excel, date_from_excel)
        
        image_num = 0
        for i in range(0, copy_num):
            student_num_from_excel = ex.get_student_number(str_sheet,list_rows[i])
            date_from_excel        = ex.get_date(str_sheet,list_rows[i])
            if sc.check_img(os.getcwd(),image_suffix,student_num_from_excel,date_from_excel):
                image_num += 1
        if image_num != copy_num:
            tkinter.messagebox.showerror('Error','Image missing !')
            return None
        
        for i in range(0,copy_num):
            doc                    = Document(doc_from)
            class_row_from_excel   = ex.get_class_row(str_sheet,list_rows[i])
            date_from_excel        = ex.get_date(str_sheet,list_rows[i])
            student_num_from_excel = ex.get_student_number(str_sheet,list_rows[i])
            img_path               = sc.get_img_path(os.getcwd(),image_suffix, student_num_from_excel, date_from_excel)
            
            table_replace(doc, str_sheet, class_row_from_excel, list_rows[i], img_path)
            paragraph_replace(doc, str_sheet, list_rows[i])
            
            student_name_from_excel = ex.get_student_name(str_sheet,list_rows[i])
            date_from_excel         = ex.get_date(str_sheet,list_rows[i])
            root_dir                = os.getcwd()
            doc_to                  = root_dir+"\\feedback\\"+student_name_from_excel+date_from_excel+".docx"
            doc.save(doc_to)
            
            print(doc_to+" ok!")
    except:
        ex.excel_close()
        traceback.print_exc()

def main():
    root = tkinter.Tk()
    root.withdraw()
    print("Generating ... \n")
    ex.excel_open()
    excel_target = tg.excel_target
    try:
        for i in range(0,len(excel_target)):
            keys = list(excel_target.keys())
            print(keys[i])
            
            values = []
            if type(excel_target.get(keys[i])) == int:
                values.append(excel_target.get(keys[i]))
            else:
                values = list(excel_target.get(keys[i]))
        
            generating(keys[i],values)
        ex.excel_close()
        if to_pdf == 1:
            for dirName, subdirList, fileList in os.walk(os.getcwd()):
                if '\\feedback' in dirName:
                    print("\r\nWord to PDF running...\r\n")
                    pdf.extern_main(dirName)
                    tkinter.messagebox.showinfo('Done','Finish !')
                    break
        else:
            tkinter.messagebox.showinfo('Done','Finish !')
    except:
        ex.excel_close()
        traceback.print_exc()
        
if __name__ == '__main__':
    main()     